<template>
    <view class="box">
		<!-- 引入 nav-bar 组件，并传递页面标题 -->
		<nav-bar :navTitle="navTitle" />
        <view class="top">
            <view 
                class="autoPay autoPayLeft" 
                :class="{ active: selectedPayType ==='00' }"
                @click="selectPayType('00')"
            >
			
                包 时 交 费
            </view>
            <view 
                class="autoPay autoPayRight" 
                :class="{ active: selectedPayType === '01' }"
				@click="selectPayType('01')"
               
            >
                包 月 交 费
            </view>
        </view>
        <view v-if="selectedPayType ==='00'">
		<!-- <view> -->
            <view class="input-row">
                <view class="label">自定金额</view>
                <input 
					:class="{ 'input-error': isAmountInvalid }"
                    placeholder="请输入充值金额" 
                    @input="handleAmountInput" 
                    type="digit" 
                    placeholder-style="color:#FE725C" 
                />
            </view>
			<view v-if="isAmountInvalid" class="error-tip">充值金额必须大于零且最多两位小数</view>
			
            <view class="input-row">
                <view class="label">备注信息</view>
                <input 
                    :class="{ 'input-error': isRemarkInvalid }"
                    placeholder="仅限文字、数字;20字以内" 
                    type="text" 
                    placeholder-style="color:#FE725C" 
                    @input="handleRemarkInput" 
                />
            </view>
            <view v-if="isRemarkInvalid" class="error-tip">备注信息，仅限文字、数字;20字以内</view>
            <view class="img" @click="goFapiaoOrder">
                <image src="/static/images/kjfp.png" mode="" />
                订单&发票
            </view>
            <button @tap="jiaofei">确认支付</button>
        </view>
    </view>
</template>

<script>
const app = getApp();
const $http = app.globalData.$http;
var config = require('../../utils/config.js');
export default {
    data() {
        return {
            picUrl: config.Config,
            amount: '',
            merchantCode: '',
            selectedPayType:'00',
            remark: '',
            isRemarkInvalid: false,
			isAmountInvalid: false,
			// 包时还是包月
			type:'',
			// 标题
			navTitle: '停车交费B2C',
			// 输入是否符合要求
			isValid:false,
        };
    },
    onLoad(options) {
        this.setData({
            merchantCode: options.merchantCode
        });
		this.type = uni.getStorageSync('paymentType');
		// 包时 00、包月01
		if(this.type =='00' ){
			this.selectedPayType = this.type;
		}else{
			this.selectedPayType = this.type;
		}
    },
    methods: {
        selectPayType(type) {
			console.log('type: ',type,'this.type: ',this.type)
			if(this.type !=type){
				if(type == '00'){
					uni.showToast({
					    title: '您不是包时用户！',
					    icon: 'none'
					});
				}else{
					uni.showToast({
					    title: '您不是包月用户！',
					    icon: 'none'
					});
				}
			}
        },
        goFapiaoOrder: function () {
            if (uni.getStorageSync('token') == '') {
                uni.showToast({
                    title: '您还未登录，请先登录',
                    icon: 'none'
                });
                setTimeout(function () {
                    uni.navigateTo({
                        url: '/pages/login/index'
                    });
                }, 1200);
            } else {
                uni.navigateTo({
                    url: '/pages/fapiaoAndOrder/index'
                });
            }
        },
		
		handleAmountInput(e) {
			let value = e.detail.value;
			const originalValue = value;

			// 过滤非数字和非小数点字符
			value = value.replace(/[^\d.]/g, '');

			// 处理多个小数点
			const dotCount = (value.match(/\./g) || []).length;
			if (dotCount > 1) {
				value = value.slice(0, value.lastIndexOf('.'));
			}

			// 处理以小数点开头的情况
			if (value.startsWith('.')) {
				value = '0' + value;
			}

			// 验证金额是否大于零且小数位数不超过两位
			this.isValid = value!== '' && parseFloat(value) > 0;
			console.log('打印isValid：',this.isValid);
			
			if (value.includes('.')) {
				const decimalPart = value.split('.')[1];
				console.log('打印decimalPart：',decimalPart);
				this.isValid = this.isValid && decimalPart.length <= 2;
			}
			
			this.isAmountInvalid =!this.isValid;
			console.log('打印：',this.isAmountInvalid);

			if (originalValue!== value ||!this.isValid) {
				this.amount = '';
				// let message = '充值金额必须大于零且最多两位小数';
				// if (originalValue!== value) {
				//     message = '请输入有效的数字金额，最多两位小数';
				// }
				// uni.showToast({
				//     title: message,
				//     icon: 'none'
				// });
			} else {
				this.amount = value;
			}
		},
		
        handleRemarkInput(e) {
            const value = e.detail.value;
            const isValid = /^[a-zA-Z0-9\u4e00-\u9fff]{0,20}$/.test(value);
            this.setData({
                remark: value,
                isRemarkInvalid:!isValid
            });
        },
        jiaofei() {
			if (this.isRemarkInvalid || this.isAmountInvalid) {
				uni.showToast({
					title: '请按照要求输入，否则不能充值',
					icon: 'none'
				});
				return;
			}
			if (this.amount =='') {
				uni.showToast({
					title: '请输入有效的数字金额，最多两位小数',
					icon: 'none'
				});
				return;
			}
			
			// 包时00或者包月01
            $http
               .payment({
                    "channel": "WXPAY",
                    "merchantCode": "EW_N9479011740",
                    "openId": uni.getStorageSync('openId'),
                    "orderSource": "1",
                    "orderType": this.type,
                    "subAppId": "wx86595b5f9ea5240c",
                    "totalAmount": parseFloat(this.amount),
                    "tradeType": "WX_LITE",
                    "remark": this.remark,
					"body": "停车费",
					"subject":"停车费"
                })
               .then((res) => {
                    console.log('打印返回的res信息：', res);
                    if (res.code == 200) {
                        const payData = JSON.parse(res.data.payData);
                        const packageValue = payData['package'];
                        console.log('packageValue：', packageValue);
                        wx.requestPayment({
                            timeStamp: payData.timeStamp,
                            nonceStr: payData.nonceStr,
                            'package': packageValue,
                            signType: payData.signType,
                            paySign: payData.paySign,
                            success(res) {
                                console.log('支付成功', res);
								// 跳转到订单发票页面
								uni.navigateTo({
									url: '/pages/fapiaoAndOrder/index'
								});
                            },
                            fail(res) {
                                console.log('支付失败', res);
                            }
                        });
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'error'
                        });
                    }
                });
        }
    }
};
</script>

<style>
	
    /* 引入HarmonyOS Sans字体 */
    @font-face {
        font-family: 'HarmonyOS Sans';
        src: url('/static/fonts/HarmonyOS_Sans_Bold.ttf') format('truetype'); /* 请根据实际字体文件路径和格式修改 */
        font-weight: 500;
        font-style: normal;
    }

.box {
        width: 700rpx;
        margin: 0 auto;
        padding-top: 200rpx; /* 进一步增大顶部内边距，给.top 留出更多空间 */
    }

.box input {
    border: 2rpx solid #ff6e00;
    height: 80rpx;
    width: 100%;
    border-radius: 16rpx;
    padding: 0 10rpx;
    font-size: 32rpx;
    box-sizing: border-box;
}

.box button {
    height: 90rpx;
    line-height: 90rpx;
    background-color: #fe725c;
    color: #fff;
    font-size: 32rpx;
    position: absolute;
    bottom: 300rpx;
    width: 700rpx;
    box-sizing: border-box;
}

.box.remark {
    margin-top: 5%;
}

.img {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #231815;
    position: absolute;
    width: 700rpx;
    bottom: 500rpx;
}

.img image {
    width: 49rpx;
    height: 46rpx;
    margin-right: 10rpx;
}

.remark {
    font-size: 24rpx;
    margin-top: 20rpx;
    font-weight: 300;
}

.no-border-input {
    border: 0 !important;
    -webkit-appearance: none; /* 移除默认样式 */
}

.top {
    height: 60px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.autoPay {
    border: 1px solid #EB5A19;
    width: 48%; /* 增加宽度 */
    height: 70rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    font-size: 30rpx;
    color: #EB5A19; /* 选中状态的文字颜色 */
}

.autoPayLeft {
    border-top-left-radius: 10px; /* 设置左上角圆角 */
    border-bottom-left-radius: 10px; /* 设置左下角圆角 */
}

.autoPayRight {
    border-top-right-radius: 10px; /* 设置左上角圆角 */
    border-bottom-right-radius: 10px; /* 设置左下角圆角 */
}

.autoPay.active {
    background-color: #EB5A19; /* 选中状态的填充色 */
    color: white; /* 选中状态的文字颜色 */
}

.input-row {
    display: flex;
    align-items: center;
    margin-top: 20rpx;
}

/* .label {
    margin-right: 10rpx;
    width: 30%;
    font-weight: bold;
} */


.label {
    margin-right: 10rpx;
    width: 30%;
    font-weight: bold;
    font-family: 'HarmonyOS Sans'; /* 应用字体 */
    font-weight: 500; /* 应用字重 */
    line-height: 19px; /* 应用行高 */
    letter-spacing: 0px; /* 应用字间距 */
    text-align: left; /* 应用对齐方式 */
}

.input-error {
    border-color: red;
    border-width: 5rpx !important; /* 加粗边框 */
}
.error-tip {
    color: red;
    font-size: 25rpx;
    margin-top: 5rpx;
    text-align: left;
    padding-left: 25%;
    font-family: 'HarmonyOS Sans'; /* 应用字体 */
    font-weight: 500; /* 应用字重 */
    line-height: 38rpx; /* 应用行高 */
    letter-spacing: 0px; /* 应用字间距 */
    text-align: left; /* 应用对齐方式 */
}
</style>
</style>